import { Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { userLog } from '@/modules/log/entities/log.entity';
import { Brackets, Repository } from 'typeorm';
import { Logger } from 'winston';
import { GetLogDto, logDto } from '@/modules/log/dto/log.dto';

@Injectable()
export class LogService {
  constructor(
    @InjectRepository(userLog)
    private logRepository: Repository<userLog>,
    @Inject('Logger') private logger: Logger,
  ) {}
  //分页查询
  async getLogsByPage(queryDto: GetLogDto): Promise<{ list: userLog[], total: number, pageNo: number, pageSize: number }> {
    const { search, pageSize = 10, pageNo = 1 ,sort,orderBy} = queryDto;

    const queryBuilder = this.logRepository.createQueryBuilder('log');

    queryBuilder.select([
      'log.id',
      'log.userId',
      'log.username',
      'log.method',
      'log.path',
      'log.ip',
      'log.device',
      'log.os',
      'log.browser',
      'log.status',
      'log.uploadTime',
      'log.updateTime'
    ]);

    if (search) {
      queryBuilder.where(new Brackets(qb => {
        qb.where("log.username LIKE :search", { search: `%${search}%` })
          .orWhere("log.method LIKE :search", { search: `%${search}%` })
          .orWhere("log.path LIKE :search", { search: `%${search}%` })
          .orWhere("log.ip LIKE :search", { search: `%${search}%` })
          .orWhere("log.device LIKE :search", { search: `%${search}%` })
          .orWhere("log.os LIKE :search", { search: `%${search}%` })
          .orWhere("log.browser LIKE :search", { search: `%${search}%` })
          .orWhere("log.status LIKE :search", { search: `%${search}%` })
          .orWhere("log.errDetail LIKE :search", { search: `%${search}%` })
          .orWhere("log.userId LIKE :search", { search: `%${search}%` });
      }));
    }

    queryBuilder.skip((pageNo - 1) * pageSize);
    queryBuilder.take(pageSize);

    //判断排序字段是否存在，不存在则默认按照id排序
    if(orderBy){
      queryBuilder.orderBy(`log.${orderBy}`,sort);
    }else {
      queryBuilder.orderBy('log.id',sort);
    }

    const [list, total] = await queryBuilder.getManyAndCount();

    return {
      list,
      total,
      pageNo,
      pageSize,
    };
  }

  //创建日志
  async createLog(logDto: logDto): Promise<userLog> {
    const newLog = this.logRepository.create(logDto);
    return await this.logRepository.save(newLog);
  }

  //删除所有日志
  async deleteAllLogs(): Promise<void> {
    await this.logRepository.clear();
  }

  //查询单个
  async getLog(id: number): Promise<userLog> {
    if (isNaN(id)) {
      throw new Error('id参数必须是数字');
    }

    return await this.logRepository.findOne({ where: { id }});
  }
  //删除单个
  async deleteLog(id: number): Promise<void> {
    await this.logRepository.delete(id);
  }
}